package com.visionet.school.app.web.web.wechat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.visionet.school.app.web.common.utils.Sha1Util;
import com.visionet.school.app.web.common.utils.SignUtils;
import com.visionet.school.app.web.common.web.WebContextFactory;
import com.visionet.school.app.web.entity.enums.LoginType;
import com.visionet.school.app.web.entity.enums.UserStatus;
import com.visionet.school.app.web.entity.user.User;
import com.visionet.school.app.web.entity.vo.LoginAccountVo;
import com.visionet.school.app.web.repository.member.MemberClassRepository;
import com.visionet.school.app.web.service.member.MemberRelService;
import com.visionet.school.app.web.service.member.MemberService;
import com.visionet.school.app.web.service.user.UserService;
import com.visionet.school.app.web.service.wechat.WechatService;
import com.visionet.school.app.web.wechat.utils.MemberUtil;
import com.visionet.school.app.web.wechat.utils.MenuUtil;
import com.visionet.school.app.web.wechat.vo.MainVO;
import com.visionet.school.app.web.wechat.vo.MenuButtonVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 * Created by hxpeng on 2017/3/21.
 */
@Controller
@RequestMapping(value = "/wechat")
public class WeChatController {

    private static final Logger logger = LoggerFactory.getLogger(WeChatController.class);

    @Resource
    private MemberService memberService;

    @Resource
    private WechatService wechatService;

    @Resource
    private UserService userService;

    @Resource
    private MemberRelService memberRelService;

    @Resource
    private MemberClassRepository memberClassRepository;

    /**
     * 前端loginAccount在store为空时，调用此请求
     * @return
     */
    @RequestMapping(value = "/testPath", method = RequestMethod.POST)
    public ResponseEntity<?> testPath(HttpServletRequest httpServletRequest){
        LoginAccountVo loginAccountVo = WebContextFactory.getWebContext().getLoginAccountVo();
        if(loginAccountVo == null){
            return new ResponseEntity(null,HttpStatus.BAD_REQUEST);
        }
        if(StringUtils.isBlank(loginAccountVo.getMemberId())){
            User user = userService.findOneByOpenId(loginAccountVo.getOpenId());
            if(user != null){
                logger.info("userInfo:"+user.toString());
                loginAccountVo = wechatService.getLoginAccountVo(user);
            }
        }
        logger.info("loginAccountVo:"+loginAccountVo.toString());
        Map<String,Object> map = new HashMap<>();
        map.put("loginAccountVo",loginAccountVo);
        return new ResponseEntity(map,HttpStatus.OK);
    }

    /**
     * 微信接入
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/servletMain", method = RequestMethod.GET)
    public @ResponseBody String servletMain(HttpServletRequest request, HttpServletResponse response) {
        // 微信加密签名
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");

        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        if (SignUtils.checkSignature(signature, timestamp, nonce)) {
            try {
                response.getWriter().write(echostr);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * 微信验证回调url/微信拦截器
     * @param request
     * @return
     */
    @RequestMapping(value="/auth")
    public String auth(HttpServletRequest request){
        logger.info("进入授权方法==================================");
        String openId;
        //用户同意授权，获取code
        String code = request.getParameter("code");
        if(StringUtils.isNotBlank(code)){
            //获取code，调用接口获取openId;
            String resultStr = wechatService.GetAccessTokenString(code);
            JSONObject objjson = JSONObject.parseObject(resultStr);
            openId = objjson.getString("openid");
            if(StringUtils.isNotBlank(openId)){
                //查询微信用户信息
                String accessToken = objjson.getString("access_token");
                String wxUserInfo = wechatService.GetUserInfo(accessToken, openId);
                JSONObject wxUserInfoObj = JSONObject.parseObject(wxUserInfo);
                //查询是否已经绑定成员
                User user = userService.findOneByOpenId(openId);
                if(user == null){
                    user = new User();
                    user.setLoginName(openId);
                    user.setLastLoginTime(new Date());
                    user.setIsDeleted("0");
                    user.setLoginType(LoginType.WECHAT.toKey());//微信登陆
                    user.setStatus(UserStatus.NORMAL.toKey());
                }else{
                    user.setLastLoginTime(new Date());
                }
                //微信用户可能会修改个人信息，所以每次进入网页重新赋值下
                user.setSex(wxUserInfoObj.getString("sex"));
                user.setProfile(wxUserInfoObj.getString("headimgurl"));
                user.setUnionId(wxUserInfoObj.getString("unionid"));

                logger.info("userinfo:" + user.toString());
                user = userService.save(user);
                LoginAccountVo loginAccountVo = wechatService.getLoginAccountVo(user);
                WebContextFactory.getWebContext().setLoginAccountVo(loginAccountVo);
            }
        }
        return "redirect:" + MainVO.wechatUrl;
    }


    /**
     * 使用注解
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/wechatSdkAuth", method = RequestMethod.POST)
    public ResponseEntity<?> wechatSdkAuth(@RequestBody JSONObject jsonObject){
        String url = jsonObject.getString("url");
        if(StringUtils.isNotBlank(url)){
            Map<String,String> map = new HashMap<>();
            String noncestr = Sha1Util.getNonceStr();
            String timestamp = Sha1Util.getTimeStamp();
            String appId = MainVO.appid;

            SortedMap<String, String> signParams = new TreeMap<>();
            signParams.put("noncestr", noncestr);
            signParams.put("timestamp", timestamp);
            signParams.put("jsapi_ticket", wechatService.getJsapiTicket().getJsapiTicket());
            signParams.put("url", url);
            String signature;
            try {
                signature = Sha1Util.createSHA1Sign(signParams);
                map.put("appId", appId);
                map.put("timestamp", timestamp);
                map.put("noncestr", noncestr);
                map.put("signature", signature);
            } catch (Exception e) {
                throw new RuntimeException("[校验微信SDK,生成签名错误：]" + e.getMessage());
            }
            return new ResponseEntity(map, HttpStatus.OK);
        }
        return new ResponseEntity(null, HttpStatus.OK);
    }

    @RequestMapping(value = "/downloadImg", method = RequestMethod.GET)
    public ResponseEntity<?> downloadImg(String media_id){
        try{
            Map<String,Object> map = new HashMap<>();
            String url= MainVO.GetMediaUrl("get",media_id);
            URL u = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            conn.setRequestMethod("GET");
            conn.connect();
            BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
            String content_disposition = conn.getHeaderField("content-disposition");
            //微信服务器生成的文件名称
            String file_name ="";
            String[] content_arr = content_disposition.split(";");
            if(content_arr.length  == 2){
                String tmp = content_arr[1];
                int index = tmp.indexOf("\"");
                file_name =tmp.substring(index+1, tmp.length()-1);
            }
            //生成不同文件名称
            File file = new File(file_name);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            byte[] buf = new byte[2048];
            int length = bis.read(buf);
            while(length != -1){
                bos.write(buf, 0, length);
                length = bis.read(buf);
            }
            bos.close();
            bis.close();
            map.put("file", file);
            return new ResponseEntity(map, HttpStatus.OK);
        }catch (IOException e){
            e.printStackTrace();
        }
        return new ResponseEntity(null, HttpStatus.OK);
    }


    /**
     * 设置个性化菜单
     * @return
     */
    @RequestMapping(value = "/individuationMenu", method = RequestMethod.POST)
    public ResponseEntity<?> individuationMenu(@RequestBody JSONObject jsonObject){
        //默认菜单
        String defaultJson = "";
        //教师个性化菜单
        String teacherJson = "{'button':[{'type':'view','name':'首页','url':'http://www.hxpeng.com/wechat/','sub_button':[]},{'name':'班级园地','sub_button':[{'type':'view','name':'家长嘱托','url':'http://www.hxpeng.com/wechat/member/teacherEntrustList','sub_button':[]},{'type':'view','name':'留言','url':'http://www.hxpeng.com/wechat/member/leaveMsg','sub_button':[]},{'type':'view','name':'班级圈子','url':'http://www.hxpeng.com/wechat/dynamic/index','sub_button':[]},{'type':'view','name':'公告','url':'http://www.hxpeng.com/wechat','sub_button':[]},{'type':'view','name':'宝宝表现','url':'http://www.hxpeng.com/wechat','sub_button':[]}]},{'name':'我的信息','sub_button':[{'type':'view','name':'个人信息','url':'http://www.hxpeng.com/wechat','sub_button':[]},{'type':'view','name':'班级成员','url':'http://www.hxpeng.com/wechat','sub_button':[]}]}],'matchrule':{'tag_id':'100'}}";
        //家长个性化菜单
        String parentJson = "{'button':[{'type':'view','name':'首页','url':'http://www.hxpeng.com/wechat/','sub_button':[]},{'name':'宝宝天地','sub_button':[{'type':'view','name':'我要嘱托','url':'http://www.hxpeng.com/wechat/entrust/create/','sub_button':[]},{'type':'view','name':'查看留言','url':'http://www.hxpeng.com/wechat/msg/list','sub_button':[]},{'type':'view','name':'班级圈子','url':'http://www.hxpeng.com/wechat/dynamic/index','sub_button':[]},{'type':'view','name':'公告','url':'http://www.hxpeng.com/wechat/class/classNotice','sub_button':[]},{'type':'view','name':'宝宝表现','url':'http://www.hxpeng.com/wechat/member/assessReport/','sub_button':[]}]},{'name':'家庭信息','type':'view','url':'http://www.hxpeng.com/wechat/member/mine','sub_button':[]}],'matchrule':{'tag_id':'101'}}";
        String json = jsonObject.getString("json");
        if(StringUtils.isNotBlank(json)){
            String resultJson = MenuUtil.individuationMenu(json);
            Map<String,String> map = new HashMap<>();
            map.put("resultJson",resultJson);
            return new ResponseEntity(map, HttpStatus.OK);
        }
        return new ResponseEntity(null, HttpStatus.OK);


    }

}
